<template>
  <a-form
    layout="inline"
    ref="formExpertRef"
    :colon="false"
    :model="formState"
    :labelCol="{ span: 8 }"
    :wrapperCol="{ span: 16 }"
  >
    <searchForm
      :num="Object.keys(formState).length"
      @searchTable="searchTable(true)"
      @resetForm="resetForm"
      @getTableHeight="getTableHeight"
    >
      <template #search-title>
        <div style="display: inline-block">审核管理</div>
      </template>
      <template #form_1>
        <a-form-item label="手机号" name="phone">
          <a-input
            v-model:value="formState.phone"
            placeholder="请输入"
            class="formWidth"
            allowClear
          />
        </a-form-item>
      </template>
      <template #form_2>
        <a-form-item label="所属企业" name="entName">
          <a-input
            v-model:value="formState.entName"
            placeholder="请输入"
            class="formWidth"
            allowClear
          />
        </a-form-item>
      </template>
      <template #form_3>
        <a-form-item name="auditStatus" label="状态" has-feedback>
          <a-select v-model:value="formState.auditStatus">
            <a-select-option
              :value="select.value"
              v-for="select in stateOptions"
              :key="select.value"
              >{{ select.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
      </template>
      <template #form_4>
        <a-form-item name="applyTime" label="申请时间">
          <a-range-picker
            v-model:value="formState.applyTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
      </template>
    </searchForm>
  </a-form>
  <a-table
    bordered
    row-key="id"
    height="50vh"
    :scroll="{
      y: '60vh'
    }"
    :data-source="data"
    :columns="columns"
    :pagination="{
      pageSize: query.pageSize,
      current: query.pageNum,
      total: total,
      showTotal: (total: number) => `共${total}条数据`,
      showSizeChanger: true,
      showQuickJumper: true,
      onChange: onPageChanged
    }"
  >
  </a-table>
  <TeamManageDialog
    title="创建团队"
    :confirm-loading="confirmLoading"
    v-model:visible="dialogVisible"
    :form="dialogForm"
    :is-phone-readonly="true"
    @handleOk="handleOk"
  />

  <a-modal v-model:visible="rejectVisible" title="提醒" @ok="handleReject">
    您要拒绝{{ rejectForm.phone }}({{ rejectForm.entName }})的试用申请吗？
  </a-modal>
</template>

<script setup lang="ts">
import { message as msgHelper } from 'ant-design-vue'
import { ref, onMounted, reactive, h } from 'vue'
import type { AuditManageColumn, IParam, AuditVO } from '@/api/type'
import {
  apiAuditList,
  type AuditListParams,
  type TeamForm,
  apiAuditTeamAdd,
  apiAuditReject
} from '@/api/manage'
import TeamManageDialog from '@/components/TeamManageDialog.vue'
import { getFutureDate } from '@/utils'

const data = ref<Array<AuditVO>>([])
const query = ref<IParam>({
  pageNum: 1,
  pageSize: 20
})
const total = ref<number>(0)

function onPageChanged(page: number, pageSize: number) {
  query.value.pageNum = page
  query.value.pageSize = pageSize
  getList()
}

const getList = async () => {
  try {
    const { applyTime, ...rest } = formState
    const listParam: AuditListParams = {
      ...rest,
      ...query.value,
      beginTime: applyTime?.[0] || '',
      endTime: applyTime?.[1] || ''
    }
    const res = await apiAuditList(listParam)
    console.log(res)
    data.value.splice(0)
    if (!res.data?.entity.rows) return
    const respData = res.data.entity
    data.value.push(...respData.rows)
    total.value = respData.total
  } catch (e) {
    console.log(e)
  }
}
onMounted(() => {
  getList()
})

const tableHeight = ref<number>()
// 重置表单
const formExpertRef = ref()
const resetForm = () => {
  formExpertRef.value.resetFields()
  searchTable()
}
//表格是否可滚动高度
function getTableHeight(height: number) {
  tableHeight.value = height
}
//查询
async function searchTable(isSearchBtn?: Boolean) {
  console.warn(formState, 'formState')
  query.value.pageNum = 1
  getList()
}
const stateOptions = [
  {
    value: '',
    label: '全部'
  },
  {
    value: 0,
    label: '待审核'
  },
  {
    value: 1,
    label: '已通过'
  },
  {
    value: 2,
    label: '已拒绝'
  }
]

const formState = reactive({
  phone: '',
  entName: '',
  auditStatus: '',
  applyTime: []
})

const dialogVisible = ref(false)
const confirmLoading = ref(false)
const dialogForm = ref<TeamForm>({
  phone: '',
  teamName: '',
  entName: '',
  peopleLimit: 10,
  expiredTime: getFutureDate(),
  authorityStatus: 0,
  formulaAuthority: 0,
  applyId: ''
})
const handleOk = async (form: TeamForm) => {
  confirmLoading.value = true
  try {
    const { data } = await apiAuditTeamAdd(form)
    if (data.code === '200') {
      msgHelper.info(data.message)
      dialogForm.value = {
        phone: '',
        teamName: '',
        entName: '',
        peopleLimit: 10,
        expiredTime: getFutureDate(),
        authorityStatus: 0,
        formulaAuthority: 0,
        applyId: ''
      }
      dialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.log(error)
  } finally {
    confirmLoading.value = false
  }
}

const rejectVisible = ref(false)
const rejectForm = ref({
  phone: '',
  entName: '',
  applyId: ''
})

const handleReject = async () => {
  if (!rejectForm.value.applyId) return
  const { data } = await apiAuditReject({ applyId: rejectForm.value.applyId })
  msgHelper.info(data.message)
  rejectForm.value = {
    phone: '',
    entName: '',
    applyId: ''
  }
  rejectVisible.value = false
  getList()
}

const columns = ref<Array<AuditManageColumn>>([
  {
    title: '姓名',
    dataIndex: 'name',
    width: 200
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: 200
  },
  {
    title: '所属企业',
    dataIndex: 'entName',
    width: 200
  },
  {
    title: '职位',
    dataIndex: 'position',
    width: 200
  },
  {
    title: '说明',
    dataIndex: 'description',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'auditStatus',
    width: 200,
    customRender: ({ record }) => {
      const state = stateOptions.find((c) => c.value === record.auditStatus)
      return state?.label || '--'
    }
  },
  {
    title: '申请时间',
    dataIndex: 'createdTime',
    width: 200
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
    customRender: ({ record }) => {
      // const record: AuditVO = opt.record as AuditVO
      // if(record.isSuperManager) return <Space />
      if (record.auditStatus === 0) {
        return h('span', {}, [
          h(
            'a',
            {
              style: {
                'margin-right': '10px'
              },
              onClick: () => {
                console.warn('opt', record)
                dialogForm.value.applyId = record.id || ''
                dialogForm.value.phone = record.phone
                dialogForm.value.entName = record.entName
                dialogForm.value.teamName = record.entName
                dialogForm.value.expiredTime = getFutureDate()
                dialogVisible.value = true
              }
            },
            '通过'
          ),
          h(
            'a',
            {
              onClick: () => {
                console.warn('opt', record)
                rejectForm.value.applyId = record.id || ''
                rejectForm.value.phone = record.phone
                rejectForm.value.entName = record.entName
                rejectVisible.value = true
              }
            },
            '拒绝'
          )
        ])
      }
      return ''
    }
  }
])
</script>

<style scoped></style>
